/********************************************************************
	created:	2021/03/1
	filename: 	httpParse.h
	author:		汪伟
*********************************************************************/

#ifndef HTTPSERVER_PARSER_HH
#define HTTPSERVER_PARSER_HH


#include <map>
#include "Data.h"
#include "internal.h"

#define HTTPUTIL_BUFFER_SIZE		32*1024


size_t GetFileSize(const char* filename);

char* GetFileModificationTime(const char* filename, char* timeNow);

char* GetFileCreateTime(const char* filename, char* timeNow);

class CHttpBuffer
{
public:
	CHttpBuffer(int nMaxLen = HTTPUTIL_BUFFER_SIZE)
	{
		m_chars = (char*)malloc(nMaxLen);
		m_MaxLen = nMaxLen;
		m_lengh = 0;
	
	}

	void append_data(const char* data, size_t size)
	{
		if (m_lengh + size > m_MaxLen) {
			m_lengh = 0;
		}

		memcpy(m_chars + m_lengh, data,size);
		m_lengh = m_lengh + size;
	}

	void reset_data(const char* data)
	{
		if (m_lengh > 0 && data != m_chars){
			memmove(m_chars,data,m_lengh);
		}
	}

	virtual ~CHttpBuffer(){
		SAFE_FREE (m_chars);
	}
public:
	char*		m_chars;
	size_t		m_lengh;
	size_t		m_MaxLen;
};

/////////////////////////////////////////////////////////////////////////////

class CHttpResponse
{
public:
	CHttpResponse() {}
	virtual ~CHttpResponse() {}
public:

	static int make( char* szBuffer,int nContentLen,const char* szContentType);
	static int make(char*  szBuffer, FILE* pFile, const char* sFileName,int nFilelen);
	static int make_download(char* szBuffer, const char* sFileName, int nFilelen);
public:
	 static void make_200(CData& strResp);
	 static void make_404_error(CData& strResp);
	 static void make_302_error(const CData& strLocation, const CData& strMoveTo, CData& strResp);
};

enum HttpMethodType {
	HTTP_METHOD_NONE,
	HTTP_METHOD_GET,
	HTTP_METHOD_POST,
	HTTP_METHOD_OPTIONS,
	HTTP_METHOD_RESP
};

class CHttpParser
{
public:
	CHttpParser();

	virtual ~CHttpParser();

	virtual int	Clear();
	virtual int	GetMethod();
	virtual int	GetContentLength();
	virtual const char* GetContentType();
	virtual const char* GetAuthorization();

	virtual const char* get_uri();
	virtual const char* get_object();
	virtual const char* get_tpfield(const char* szKeys);
	virtual const char* get_paramField(const char* szKeys);
	
	virtual int	 parse(const char* szHttpParam, int nLen);
	virtual int  parsePostParam();
	virtual int  parseGetParam();
	int			ParseLine(CData& lineData, int lineNum);
	void		SetContent(const char* key, const char* content, int len);
	CData&  GetContent(){ return m_Context; }
	CData getHeader();


private:
	int			m_method;
	CData		m_headers;
	CData		m_Context;
	std::map    <CData, CData> m_FieldMap;
	std::map    <CData, CData> m_ParamMap;
	CData		m_type;
};

#endif
